package firsttest.test.fragment2;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private FragmentManager mManager;
    private FragmentA fragmentA;
    private FragmentB fragmentB;
    /**
     * 使用碎片小弟
     */
    private TextView mTxtTitle;
    private RelativeLayout mFragment;
    /**
     * 隐藏B
     */
    private Button mBtnB;
    /**
     * 显示B
     */
    private Button mBtnB1;
    /**
     * 替换B
     */
    private Button mBtnReplace;
    private Fragment fragment;
    private FragmentC fragmentC;

    //动态使用
    //创建两个fragment
    //获得管理器
    //快开始事务
    //通过动态放法操作fragment add，ewmove
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        fragmentA = new FragmentA();
        fragmentB = new FragmentB();
        fragmentC = new FragmentC();
        //获得管理器
        mManager = getSupportFragmentManager();
        //开启事物
        FragmentTransaction transac = mManager.beginTransaction();
        //通过事物把fragment添加到事物中
        transac.add(R.id.fragment, fragmentA).add(R.id.fragment, fragmentB);
        transac.commit();
        mBtnB = (Button) findViewById(R.id.btnB);
        mBtnB.setOnClickListener(this);
        mBtnB1 = (Button) findViewById(R.id.btnB1);
        mBtnB1.setOnClickListener(this);
        mBtnReplace = (Button) findViewById(R.id.btn_replace);
        mBtnReplace.setOnClickListener(this);
        mTxtTitle = (TextView) findViewById(R.id.txt_title);
        mFragment = (RelativeLayout) findViewById(R.id.fragment);
        mTxtTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mManager.beginTransaction().remove(fragmentB).commit();
                fragmentB.setName("dfghfdsfgh");
            }
        });
    }
    public void setmTxtTitle(String newStr){
        mTxtTitle.setText(newStr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btnB:
                mManager.beginTransaction().hide(fragmentB).commit();
                break;
            case R.id.btnB1:
                mManager.beginTransaction().show(fragmentB).commit();
                break;
            case R.id.btn_replace:
                mManager.beginTransaction().replace(R.id.fragment,fragmentC).commit();
                break;
        }
    }
}
